package cn.edu.niit.studyspace.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import org.litepal.crud.DataSupport;

import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.adapter.CourseSelectAdapter;
import cn.edu.niit.studyspace.bean.Course;
import cn.edu.niit.studyspace.bean.SchoolTableItemBean;

public class SchoolTimeTableItemModifyActivity extends AppCompatActivity
    implements CourseSelectAdapter.OnItemClick {
  private long id;
  private CourseSelectAdapter adapter;
  private List<Course> items;
  private RecyclerView rvCourse;
  private AlertDialog.Builder builder;
  AlertDialog dialog;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_school_time_table_item_modify);
    initData();
    initView();
  }

  private void initData() {
    Intent intent = getIntent();
    id = intent.getLongExtra("dId", 0);
    Log.e("id:", id + "");
    items = DataSupport.findAll(Course.class, true);
    adapter = new CourseSelectAdapter(this, items, this::onItemClick);
  }

  private void initView() {
    rvCourse = findViewById(R.id.rv_course_select);
    rvCourse.setAdapter(adapter);
    if (items.size() == 0) {
      builder =
          new AlertDialog.Builder(this)
              .setIcon(R.mipmap.ic_launcher)
              .setTitle("提示")
              .setMessage("课程为空，是否前去创建？")
              .setPositiveButton(
                  "确定",
                  (dialogInterface, i) ->
                      startActivity(
                          new Intent(
                              SchoolTimeTableItemModifyActivity.this, NewCourseActivity.class)))
              .setNegativeButton(
                  "取消",
                  (dialogInterface, i) -> {
                    dialogInterface.dismiss();
                  });
      AlertDialog dialog = builder.create();
      dialog.show();
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    items = DataSupport.findAll(Course.class, true);
    adapter.notifyData(items);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (dialog != null) {
      if (dialog.isShowing()) {
        dialog.dismiss();
      }

      dialog = null;
    }
  }

  @Override
  public void onItemClick(View view, int position) {
    SchoolTableItemBean itemBean = new SchoolTableItemBean();
    Course course = items.get(position);
    itemBean.setTeacher(course.getTeacher());
    itemBean.setPlace(course.getPlace());
    itemBean.setName(course.getName());
    itemBean.setInfo(course.getInfo());
    itemBean.update(id);
    this.finish();
  }
}
